<template>
  <view class="page-container">
    <!-- 顶部标题 -->
    <view class="header">
      <view class="title">选择图片</view>
      <view class="subtitle">从 {{ exhibitionTitle }} 中选择图片</view>
    </view>

    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-container">
      <text class="loading-text">加载图片中...</text>
    </view>

    <!-- 空状态 -->
    <view v-else-if="images.length === 0" class="empty-container">
      <view class="empty-icon">🖼️</view>
      <text class="empty-text">该展览暂无图片</text>
      <text class="empty-hint">请先为展览添加图片</text>
      <button class="add-btn" @click="addImages">添加图片</button>
    </view>

    <!-- 图片网格 -->
    <view v-else class="image-grid">
      <view 
        v-for="(image, index) in images" 
        :key="index"
        class="image-item"
        :class="{ selected: selectedImages.includes(image.imageUrl) }"
        @click="toggleImageSelection(image.imageUrl)"
      >
        <image 
          :src="image.imageUrl" 
          mode="aspectFill"
          class="image"
        />
        <view class="selection-overlay" v-if="selectedImages.includes(image.imageUrl)">
          <view class="check-icon">✓</view>
        </view>
      </view>
    </view>

    <!-- 选择提示（有图片时展示） -->
    <view v-if="!isLoading && images.length > 0" class="select-hint">请点击图片进行选择（可多选）</view>

    <!-- 底部操作栏 -->
    <view v-if="images.length > 0" class="bottom-actions">
      <view class="selection-info">
        已选择 {{ selectedImages.length }} 张图片
      </view>
      <button 
        class="confirm-btn"
        :disabled="selectedImages.length === 0"
        @click="confirmSelection"
      >
        确认选择 ({{ selectedImages.length }})
      </button>
      <button class="add-more-btn" @click="addImages">添加图片</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getRecordDetail, uploadSingleImage } from '@/services/api/backendApi'
import { onLoad } from '@dcloudio/uni-app'

// 响应式数据
const isLoading = ref(true)
const images = ref([])
const selectedImages = ref([])
const exhibitionId = ref('')
const exhibitionTitle = ref('')

// 页面加载参数
onLoad((query) => {
  if (query.exhibitionId) {
    exhibitionId.value = query.exhibitionId
  }
  if (query.exhibitionTitle) {
    exhibitionTitle.value = decodeURIComponent(query.exhibitionTitle)
  }
})

// 页面加载时获取图片列表
onMounted(async () => {
  await loadExhibitionImages()
})

// 加载展览图片
async function loadExhibitionImages() {
  try {
    isLoading.value = true
    console.log('开始加载展览图片:', exhibitionId.value)
    const detail = await getRecordDetail(exhibitionId.value)
    console.log('✅ 展览详情返回:', detail)
    const data = detail.data || detail
    const list = data.imageList || data.images || []
    images.value = list.map(img => ({ imageUrl: img.imageUrl || img.url, imageId: img.imageId || img.id }))
    console.log('📦 归一化后的图片数量:', images.value.length)
  } catch (error) {
    console.error('加载展览图片失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 添加图片到展览
function addImages() {
  if (!exhibitionId.value) {
    uni.showToast({ title: '展览ID缺失', icon: 'none' })
    return
  }
  uni.chooseImage({
    count: 9,
    success: async (res) => {
      try {
        // 逐张上传
        const temp = res.tempFilePaths || []
        for (let i = 0; i < temp.length; i++) {
          // 使用统一封装的上传接口（绑定到该展览）
          await uploadSingleImage(temp[i], 2, exhibitionId.value)
        }
        uni.showToast({ title: '已添加', icon: 'success' })
        // 重新加载列表
        await loadExhibitionImages()
      } catch (e) {
        console.error('添加图片失败:', e)
        uni.showToast({ title: '添加失败', icon: 'none' })
      }
    }
  })
}

// 切换图片选择状态
function toggleImageSelection(imageUrl) {
  const index = selectedImages.value.indexOf(imageUrl)
  if (index > -1) {
    selectedImages.value.splice(index, 1)
  } else {
    selectedImages.value.push(imageUrl)
  }
  console.log('当前选择的图片:', selectedImages.value)
}

// 确认选择
function confirmSelection() {
  if (selectedImages.value.length === 0) {
    uni.showToast({
      title: '请至少选择一张图片',
      icon: 'none'
    })
    return
  }
  
  console.log('确认选择图片:', selectedImages.value)
  
  // 跳转到ImageGenerator，传入选择的图片和展览信息
  const exhibitionData = {
    recordId: exhibitionId.value,
    title: exhibitionTitle.value,
    galleryName: '用户展览'
  }
  
  uni.navigateTo({
    url: `/pages/upload/upload?mode=import&images=${encodeURIComponent(JSON.stringify(selectedImages.value))}&exhibition=${encodeURIComponent(JSON.stringify(exhibitionData))}`,
    success: () => {
      uni.showToast({
        title: `已选择${selectedImages.value.length}张图片`,
        icon: 'success'
      })
    },
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '跳转失败',
        icon: 'none'
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background: #1a1a1a;
  padding: 20px;
  padding-bottom: 100px; /* 为底部操作栏留出空间 */
}

.header {
  text-align: center;
  margin-bottom: 30px;
  
  .title {
    font-size: 28px;
    font-weight: 700;
    color: #ffffff;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    margin-bottom: 10px;
    letter-spacing: 1px;
  }
  
  .subtitle {
    font-size: 16px;
    color: #a0826d;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  
  .loading-text {
    font-size: 16px;
    color: #ffffff;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  
  .empty-icon {
    font-size: 64px;
    margin-bottom: 20px;
    opacity: 0.6;
  }
  
  .empty-text {
    font-size: 20px;
    color: #ffffff;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    font-weight: 600;
    margin-bottom: 10px;
  }
  
  .empty-hint {
    font-size: 14px;
    color: #a0826d;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }

  .add-btn {
    margin-top: 18px;
    background: linear-gradient(135deg, #d4af37, #f4e4bc);
    color: #ffffff;
    border: none;
    padding: 10px 20px;
    border-radius: 20px;
    font-size: 14px;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    font-weight: 600;
    box-shadow: 0 4px 12px rgba(212, 175, 55, 0.3);
    &::after { border: none; }
  }
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.image-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(212, 175, 55, 0.15);
  transition: all 0.3s ease;
  
  &.selected {
    box-shadow: 0 8px 24px rgba(212, 175, 55, 0.4);
    transform: scale(0.95);
  }
  
  .image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .selection-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(212, 175, 55, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    
    .check-icon {
      width: 40px;
      height: 40px;
      background: #d4af37;
      color: white;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      font-weight: bold;
      box-shadow: 0 4px 12px rgba(212, 175, 55, 0.5);
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95), rgba(245, 242, 237, 0.95));
  backdrop-filter: blur(20px);
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 -4px 20px rgba(212, 175, 55, 0.15);
  
  .selection-info {
    font-size: 16px;
    color: #ffffff;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    font-weight: 500;
  }
  
  .confirm-btn {
    background: linear-gradient(135deg, #d4af37, #f4e4bc);
    color: #ffffff;
    border: none;
    padding: 12px 24px;
    border-radius: 25px;
    font-size: 16px;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    font-weight: 600;
    box-shadow: 0 4px 12px rgba(212, 175, 55, 0.3);
    
    &:disabled {
      background: #e0e0e0;
      color: #999;
      box-shadow: none;
    }

    .add-more-btn {
      background: #0FFDCD;
      color: #0c0c0c;
      border: none;
      padding: 12px 16px;
      border-radius: 18px;
      font-size: 14px;
      font-weight: 600;
      &::after { border: none; }
    }
  }

.select-hint {
  text-align: center;
  margin: 10px 0 6px;
  color: #e0e0e0;
  font-size: 13px;
}
}
</style>
